using System;
using System.Collections.Generic;
using System.Text;
using Evolution.Engine.Interfaces;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Evolution.Engine.Managers;

namespace Evolution.Engine.Objects
{
    public class Geometry : BaseObject, Evolution.Engine.Interfaces.IUpdateable, IChildRenderer, IHasMaterial, ILoadable
    {
        protected string _Asset;
        protected Model _Model;

        public Geometry(string name, string asset)
            : base(name)
        {
            _Asset = asset;
        }

        public override void LoadContent()
        {
            _Model = ResourceManager.Instance.LoadContent<Model>(_Asset);

            foreach (ModelMesh mesh in _Model.Meshes)
            {
                foreach (BasicEffect effect in mesh.Effects)
                {
                    effect.View = CameraManager.Instance.ActiveCamera.View;
                    effect.Projection = CameraManager.Instance.ActiveCamera.Projection;
                }
            }
        }

        public void RenderChildren(GameTime gameTime)
        {
            Shader shader = ShaderManager.Instance.GetShader(_Shader);

            foreach (ModelMesh mesh in _Model.Meshes)
            {
                GameEngine.Instance.Device.Indices = mesh.IndexBuffer;

                shader.Effect.Begin();

                foreach (EffectPass pass in shader.Effect.CurrentTechnique.Passes)
                {
                    pass.Begin();

                    foreach (ModelMeshPart part in mesh.MeshParts)
                    {
                        GameEngine.Instance.Device.VertexDeclaration = part.VertexDeclaration;
                        GameEngine.Instance.Device.Vertices[0].SetSource(
                            mesh.VertexBuffer,
                            part.StreamOffset,
                            part.VertexStride
                        );

                        GameEngine.Instance.Device.Textures[0] = ((BasicEffect)part.Effect).Texture;

                        GameEngine.Instance.Device.DrawIndexedPrimitives(
                            PrimitiveType.TriangleList,
                            part.BaseVertex, 0,
                            part.NumVertices,
                            part.StartIndex,
                            part.PrimitiveCount
                        );
                    }

                    pass.End();
                }

                shader.Effect.End();
            }
        }

        #region IHasMaterial Members

        public void SetMaterialProperties()
        {
        }

        #endregion
    }
}
